<?php

namespace App\Console\Commands\Order;

use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Command;

/**
 *  @usage php artisan order:expire {id?}
 */
class Expire extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:expire {id? : The ID of the order}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'expire an unpaid order';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        // 订单12小时过期
        $order_expired_minute = 12 * 60;

        $id = $this->argument('id');
        if (!empty($id)) {
            $orders = Order::whereIn('id', [$id])->get();
        } else {
            $orders = Order::where('status', 0)->orderBy('id', 'ASC')->limit(1000)->get();
        }

        $now = Carbon::now();
        foreach ($orders  as $v) {
            $order_time = new Carbon($v->created_at);

            if ($order_time->lessThan($now)) {
                if ($order_time->diffInMinutes($now) > $order_expired_minute) {
                    $v->status = 2;
                    $v->save();

                    $this->info(sprintf("订单 %s 过期", $v->orderno));
                }
            }
        }

        return Command::SUCCESS;
    }
}
